/*
 * @Description: 一个获取定位的工具类
 * @Author: yingying.fan
 * @Date: 2019-05-27 15:17:20
 * @Last Modified by: buwei.huang
 * @Last Modified time: 2019-06-11 10:13:09
 */
// import { isAndroid } from 'vue-xiaobu-utils'
// import vue from '@/main'

const LOCATION_ERROR = {
  PLUGIN_ERROR: 'plugin_error', // 插件加载失败
  GPS_NOT_OPEN: 'gps_not_open', // GPS未开启
  GPS_SERVICE_ONCE_FORBID: 'location_service_once_forbid', // GPS服务临时禁止
  GPS_SERVICE_ALWAYS_FORBID: 'location_service_always_forbid', // GPS服务始终禁止
  LOCATION_FAIL: 'location_fail' // 定位获取失败
}

let aLocation = null
let aNeedToastError = null
let vue = null

class LocationError extends Error {
  constructor(code, message) {
    super(message)
    this.code = code
  }
}

/**
 * 获取当前定位的方法
 *
 * @param {} vueModule vue模块
 * @param {Boolean} needToastError 需要toast错误
 */
async function getCurrentPosition(vueModule, needToastError = true) {
  // if (!window.prodInApp) {
  //   // return Promise.reject(
  //   //   new LocationError(LOCATION_ERROR.GPS_NOT_OPEN, '未开启定位')
  //   // )
  //   return Promise.resolve({
  //     acode: '330108',
  //     add: '浙江省杭州市滨江区江虹路692号靠近浙江歌山品悦大酒店',
  //     aname: '滨江区',
  //     cname: '杭州市',
  //     latitude: 29.07555,
  //     longitude: 119.652063,
  //     // latitude: 0,
  //     // longitude: 0,
  //     pname: '浙江省',
  //     poi: '浙江歌山品悦大酒店'
  //   })
  // }
  vue = vueModule
  aNeedToastError = needToastError

  try {
    aLocation = await vue.$Location
    // if (isAndroid()) {
    //   // 安卓直接开启服务
    //   return startGPSService().catch(error => {
    //     toastError(error)
    //     throw error
    //   })
    // } else {
    return new Promise((resolve, reject) => {
      aLocation.isGPSOpen(
        res => {
          console.log(`是否打开定位${res}`)
          if (res === true || res === 'true') {
            return startGPSService()
              .then(locationObj => {
                resolve(locationObj)
              })
              .catch(error => {
                toastError(error)
                reject(error)
              })
          } else {
            // 未开启的话跳转到ios定位设置页面
            // aLocation.openGPSSetting(() => {}, () => {})
            reject(new LocationError(LOCATION_ERROR.GPS_NOT_OPEN, '未开启定位'))
          }
        },
        () => {
          reject(new LocationError(LOCATION_ERROR.GPS_NOT_OPEN, '未开启定位'))
        }
      )
    })
    // }
  } catch (error) {
    throw new LocationError(LOCATION_ERROR.PLUGIN_ERROR, '插件加载失败')
  }
}

// 开启服务
function startGPSService() {
  return new Promise((resolve, reject) => {
    aLocation.startService(
      () => {
        // 获取定位
        getCurrentPositionByTimer(resolve, reject)
      },
      err => {
        console.error(err)
        if (err === '1') {
          // app的定位服务始终禁止
          // 如果有说明，可以打开应用设置页面
          reject(
            new LocationError(
              LOCATION_ERROR.GPS_SERVICE_ALWAYS_FORBID,
              '开启定位服务失败'
            )
          )
        } else {
          // app的定位服务临时禁止
          reject(
            new LocationError(
              LOCATION_ERROR.GPS_SERVICE_ONCE_FORBID,
              '开启定位服务失败'
            )
          )
        }
      }
    )
  })
}

// 获取定位
function getCurrentPositionByTimer(resolve, reject, timeindex = 1) {
  window.setTimeout(() => {
    aLocation.getCurrentPosition(
      res => {
        console.log('获取到的定位：' + res)
        // callback(JSON.parse(res))
        resolve(JSON.parse(res))
        // 关闭服务
        stopGPSService(Location)
      },
      error => {
        // timeindex++
        console.error(error)
        if (timeindex >= 5) {
          // 关闭服务
          stopGPSService(Location)
          reject(
            new LocationError(LOCATION_ERROR.LOCATION_FAIL, '获取定位失败')
          )
        } else {
          getCurrentPositionByTimer(resolve, reject, timeindex + 1)
        }
      }
    )
  }, 500)
}

function stopGPSService() {
  aLocation.stopService(
    () => {
      console.log('关闭定位服务成功')
    },
    err => {
      console.error(err)
    }
  )
}

function toastError(error) {
  if (aNeedToastError) {
    // vue.$toast(error.message)
    vue.$Toast.then(Toast => {
      Toast.showLongBottom(error.message)
    })
  }
}

export { getCurrentPosition, LOCATION_ERROR }
